package org.wlw.service;

import org.apache.ibatis.session.SqlSession;
import org.wlw.mapper.MovieMapper;
import org.wlw.models.Movie;
import org.wlw.models.WlwSystemException;
import org.wlw.utils.DBUtils;

import java.util.List;

public class MovieService implements IMovieService{

    @Override
    public void add(Movie movie) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            sqlSession.getMapper(MovieMapper.class).add(movie);
            sqlSession.commit();
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    @Override
    public void delete(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            sqlSession.getMapper(MovieMapper.class).delete(id);
            sqlSession.commit();
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    @Override
    public void update(Movie movie) {
        SqlSession sqlSession = null;

        try {
            sqlSession = DBUtils.openSession();
            final Movie tmovie = sqlSession.getMapper(MovieMapper.class).load(movie.getId());
            if(tmovie==null) {
                throw new WlwSystemException("更新的电影不存在!");
            }
            tmovie.setType(movie.getType());
            tmovie.setName(movie.getName());
            tmovie.setActor(movie.getActor());
            tmovie.setDirector(movie.getDirector());
            tmovie.setScore(movie.getScore());
            sqlSession.getMapper(MovieMapper.class).update(movie);
            sqlSession.commit();
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    @Override
    public Movie load(int id) {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            return sqlSession.getMapper(MovieMapper.class).load(id);
        } finally {
            DBUtils.close(sqlSession);
        }
    }

    @Override
    public List<Movie> list() {
        SqlSession sqlSession = null;
        try {
            sqlSession = DBUtils.openSession();
            return sqlSession.getMapper(MovieMapper.class).find();
        } finally {
            DBUtils.close(sqlSession);
        }
    }
}
